import com.alibaba.fastjson.JSON;
import domain.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: ylc
 * @Description:服务器返回Json字符串
 * @Date Created in 2022-07-03 14:28
 */
@WebServlet("/ajaxrequest3")
public class AjaxRequest3Json extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String jsonStr = "";
        // JDBC Connection
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        try{
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql:///StudyTest","root","root");
            String sql = "select name, age, addr from Student";
            stmt = conn.prepareStatement(sql);
            rs = stmt.executeQuery();

            List<Student> studentList = new ArrayList<>();
            while(rs.next()){
                // 取出数据
                String name = rs.getString("name");
                int age = rs.getInt("age");
                String addr = rs.getString("addr");
                // 将以上数据封装成Student对象
                Student student = new Student(name, age, addr);
                // 将Student对象放到List集合
                studentList.add(student);
            }
            // 将List集合转换为Json字符串
            jsonStr = JSON.toJSONString(studentList);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }finally {
            if(rs != null){
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(stmt != null){
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        // 响应JSON格式的字符串给前端。
        out.print(jsonStr);
    }
}
